package com.chidopi.market.bookstore.actions;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chidopi.cdf.exception.CdfException;
import com.chidopi.cdf.service.IBaseService;
import com.chidopi.cdf.struts1actions.StandardOperatorAction;
import com.chidopi.cdf.util.ModelContextFactory;
import com.chidopi.market.bookstore.domain.BookCities;
import com.chidopi.market.bookstore.domain.Subscribe4iOS;
import com.chidopi.market.bookstore.domain.Subscriptions;
import com.chidopi.market.bookstore.service.IResourceService;
import com.chidopi.market.util.FileHelper;
import com.chidopi.market.util.MessageHandler;

public class Subscribe4iOSAction extends StandardOperatorAction<Subscribe4iOS>{
	
	private static Logger logger = LoggerFactory.getLogger(Subscribe4iOSAction.class);
	
	private String RES_PATH = "";
	
	private IBaseService<Subscribe4iOS> baseService;
	
	private IResourceService resourceService;
	
	private IBaseService<BookCities> cityService;
	
	private IBaseService<Subscriptions> subscriptionService;
	
	public Subscribe4iOSAction(){
		this("");
	}
	
	@SuppressWarnings("unchecked")
	public Subscribe4iOSAction(String entryURL) {
		this.entryURL = entryURL;
		try {
			this.baseService = (IBaseService<Subscribe4iOS>)
				ModelContextFactory.get("subscribe4iOSService", IBaseService.class);
			this.resourceService = (IResourceService)
				ModelContextFactory.get("resourceService", IResourceService.class);
			this.cityService = (IBaseService<BookCities>)
				ModelContextFactory.get("bookCitiesService", IBaseService.class);
			this.subscriptionService = (IBaseService<Subscriptions>)
				ModelContextFactory.get("subscriptionsService", IBaseService.class);
			this.RES_PATH = resourceService.getBookCityResPath();
		} catch (Exception e) {
			this.baseService = null;
			logger.warn("initial", e);
		}
	}
	
	public ActionForward init(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("vo", null);
		dynaForm.set("op", null);
		
		List<BookCities> list = cityService.find(null);		
		dynaForm.set("cities", list);
		logger.info("cities:" + list);
		
		List<Subscriptions> subList = subscriptionService.find(null);
		dynaForm.set("subscriptions", subList);
		logger.info("subscriptions:" + subList);
		
		return mapping.findForward("success");
	}
	
	public ActionForward back(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward("success");
	}
	
	private static final String[] conditions = {"id", "subscribe_id", "city_id","appDevice","appBoundleID"};
	public ActionForward query(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (null == this.baseService) return mapping.findForward("error");
		StringBuffer sql = new StringBuffer();
		ArrayList<String> args = new ArrayList<String>();
		for (String cond : conditions) {
			String value = (String) request.getParameter(cond);
			if (value == null || value.trim().equals("")) continue;
			logger.debug(cond + "=" + value);
			
			if (sql.length() > 1) sql.append("and ");
			if (cond.equals("appBoundleID")) {
				sql.append("appBoundleID like ?");
				args.add("%" + value +"%");
			} else if (cond.equals("id")){
				sql.append("a.id like ?");
				args.add("%" + value +"%");
			} else if (cond.equals("city_id")){
				sql.append("a.city_id = ?");
				args.add(value);
			}else {
				sql.append(cond + " = ?");
				args.add(value);
			}
		}
		logger.debug("sql=" + sql.toString());
		List<Subscribe4iOS> list = this.baseService.find(sql.toString(),args.toArray());
		logger.debug("size=" + list.size());
		JSONArray json = JSONArray.fromObject(list);

		PrintWriter out=response.getWriter();
		logger.debug(json.toString());
        out.println(json);
        out.flush();
		return null;
	}
	
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		logger.debug("id=" + id);
		Subscribe4iOS t = this.baseService.findById(new Integer(id));
		if (null == t) {
			logger.warn("Subscribe4iOS[id={}] is deleted!!", id);
			return mapping.findForward("err");
		}
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("op", "delete");
		dynaForm.set("vo", t);
		List<BookCities> list = cityService.find(" a.ENABLE_FLAG = 'Y' ");
		dynaForm.set("cities", list);
		
		Object city_id = t.getBookCity().getId();
		List<Subscriptions> subList = subscriptionService.find(" a.ENABLE_FLAG = 'Y' and b.ID = ? ", city_id);
		dynaForm.set("subscriptions", subList);
		return mapping.findForward("success");
	}

	public ActionForward insert(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		logger.debug("id=" + id);
		Subscribe4iOS t = this.baseService.findById(id);
		
		Object city_id = null;
		
		if (null == t){ 
			t = new Subscribe4iOS();
		} else {
			city_id = t.getBookCity().getId();
		}
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("op", "insert");
		dynaForm.set("vo", t);
		
		t.setAppStorePageL(null);
		t.setAppStorePageP(null);
		
		List<BookCities> list = cityService.find(" a.ENABLE_FLAG = 'Y' ");
		dynaForm.set("cities", list);
		dynaForm.set("subscriptions", null);
		if(city_id != null){
			List<Subscriptions> subList = subscriptionService.find(" a.ENABLE_FLAG = 'Y' and b.ID = ? ", city_id);
			dynaForm.set("subscriptions", subList);
		}
		return mapping.findForward("success");
	}

	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");
		logger.debug("id=" + id);
		Subscribe4iOS t = this.baseService.findById(id);
		if (null == t) {
			logger.warn("Subscribe4iOS[id={}] is deleted!!", id);
			return mapping.findForward("err");
		}
		DynaBean dynaForm = (DynaBean) form;
		dynaForm.set("op", "update");
		dynaForm.set("vo", t);
		List<BookCities> list = cityService.find(" a.ENABLE_FLAG = 'Y' ");
		dynaForm.set("cities", list);
		
		Object city_id = t.getBookCity().getId();
		List<Subscriptions> subList = subscriptionService.find(" a.ENABLE_FLAG = 'Y' and b.ID = ? ", city_id);
		dynaForm.set("subscriptions", subList);
		return mapping.findForward("success");
	}

	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String op = request.getParameter("op");
		Integer userId = (Integer) request.getSession().getAttribute("user_id");
		logger.debug("op=" + op);
		
		Subscribe4iOS t = new Subscribe4iOS();
		DynaBean dynaForm = (DynaBean) form;
		try {
		
			PropertyUtils.copyProperties(t, dynaForm.get("vo"));
			logger.debug(t.getId() + ":" + t.getBookCity().getId() + "/" + t.getSubscribe().getId());
		} catch (Exception e) {
			logger.warn("PropertyUtils", e);
			return mapping.findForward("err");
		}
		
		String oldPageL = "";
	    String oldPageP = "";
	    
	    FormFile pageL = (FormFile)dynaForm.get("appStorePageL");
	    if(pageL != null && pageL.getFileSize() > 0){
	    	String suffix = FileHelper.getFileSuffix(pageL.getFileName());
	    	String name =  FileHelper.getRandomTimeString("ios_l_" ) + (suffix.length() > 0 ? "." + suffix : suffix); 
	    	oldPageL =t.getAppStorePageL();
		    t.setAppStorePageL(name);			    
	    }
	    
	    FormFile pageP = (FormFile)dynaForm.get("appStorePageP");
	    if(pageL != null && pageL.getFileSize() > 0){
	    	String suffix = FileHelper.getFileSuffix(pageL.getFileName());
	    	String name =  FileHelper.getRandomTimeString("ios_p_" ) + (suffix.length() > 0 ? "." + suffix : suffix); 
	    	oldPageP =t.getAppStorePageP();
		    t.setAppStorePageP(name);			    
	    }

		int ret = -1;
		String dest = "";
		FileHelper.checkPath(RES_PATH);
		if ("insert".equals(op)) {
			t.setCreate_by(userId);
		    ret = this.baseService.insert(t);
		    
		    if(ret > -1){
		    	if( pageL != null && pageL.getFileSize() > 0 ){
					dest = RES_PATH + t.getAppStorePageL();
					logger.debug("appPageL Path: " + dest);
					FileHelper.writeFile(pageL, dest);
				}
		    	
		    	if( pageP != null && pageP.getFileSize() > 0 ){
					dest = RES_PATH + t.getAppStorePageP();
					logger.debug("appPageP Path: " + dest);
					FileHelper.writeFile(pageP, dest);
				}
		    }
		} else if ("update".equals(op)) {
			t.setUpdate_by(userId);
			ret = this.baseService.update(t);
			
			if(ret > -1){
				if(pageL != null && pageL.getFileSize() > 0){
					dest = RES_PATH + t.getAppStorePageL();
					logger.debug("appPageL Path: " + dest);
					FileHelper.writeFile(pageL, dest);
					if(oldPageL !=null && oldPageL.length() > 0){
						dest = RES_PATH + oldPageL;
						logger.debug("delete oldPageL : " + dest);
						FileHelper.deleteFile(dest);
					}
				}
				
				if(pageP != null && pageP.getFileSize() > 0){
					dest = RES_PATH + t.getAppStorePageP();
					logger.debug("appPageP Path: " + dest);
					FileHelper.writeFile(pageP, dest);
					if(oldPageP !=null && oldPageP.length() > 0){
						dest = RES_PATH + oldPageP;
						logger.debug("delete oldPageP : " + dest);
						FileHelper.deleteFile(dest);
					}
				}
			}
		} else if ("delete".equals(op)) {
			t.setUpdate_by(userId);
			try{
				ret = this.baseService.delete(t);
			}catch(CdfException cex){
				MessageHandler.getInstance().processError(request, cex.getMessage());
			}
			if(ret > -1){				
				if(oldPageL != null && oldPageL.length() > 0){
					dest = RES_PATH + oldPageL;
					logger.debug("delete oldPageL : " + dest);
					FileHelper.deleteFile(dest);
				}
				if(oldPageP !=null && oldPageP.length() > 0){
					dest = RES_PATH + oldPageP;
					logger.debug("delete oldPageP : " + dest);
					FileHelper.deleteFile(dest);
				}
			}
		}
		
		if (ret > -1) {
			request.setAttribute("entryURL", entryURL);
			return mapping.findForward("success");
		}else {
			return mapping.findForward("err");
		}
	}
	
	//showPageP
	public ActionForward showPageP(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		String file = request.getParameter("file");
		if(file != null && file.length()> 0){
			String path = RES_PATH + file;			
			FileHelper.writeImageToResponse(response, path);
		}
		return null;
	}
	
	public ActionForward showPageL(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		String file = request.getParameter("file");
		if(file != null && file.length()> 0){
			String path = RES_PATH + file;			
			FileHelper.writeImageToResponse(response, path);
		}
		return null;
	}
	
	public ActionForward ajaxGetSubscriptions(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		String city_id = request.getParameter("city_id");
		String sqlwhere = " a.ENABLE_FLAG = 'Y' and b.ID = ? ";
		List<Subscriptions> subs = this.subscriptionService.find(sqlwhere,city_id);
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		if(subs != null){
			for(Subscriptions sub : subs){
				Map<String, String> map = new HashMap<String, String>();
				map.put("id", sub.getId().toString());
				map.put("name", sub.getName());
				list.add(map);
			}
		}
		JSONArray json = JSONArray.fromObject(list);
		PrintWriter out=response.getWriter();
		logger.debug(json.toString());
        out.println(json);
        out.flush();
		
		return null;
	}
}
